<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <el-button
          type="primary"
          @click="dialogVisible = true"
          icon="el-icon-plus"
          size="small"
          v-buttonLimits="'btn'"
          >添加</el-button
        >
      </template>
      <el-table :data="trademarks" border>
        <el-table-column
          prop="date"
          label="序号"
          width="80"
          type="index"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称" width="383">
        </el-table-column>
        <el-table-column prop="address" label="品牌LOGO">
          <template v-slot:default="scope">
            <img
              :src="scope.row.logoUrl"
              style="width: 100px; height: 87px"
            /> </template
        ></el-table-column>
        <el-table-column prop="address" label="操作" width="382">
          <template slot-scope="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="editTrademark(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="deleteOne(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        @size-change="setSize"
        @current-change="setCurrent"
        :current-page="current"
        :page-sizes="[3, 6, 9]"
        :page-size="pageSize"
        layout="prev, pager,next, jumper,->, sizes,total "
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      :title="formData.id ? '编辑品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      @close="closeBefore"
    >
      <el-form
        :rules="rules"
        ref="formData"
        :model="formData"
        label-width="100px"
      >
        <el-form-item prop="tmName" label="品牌名称">
          <el-input
            placeholder="请输入品牌名称"
            size="small"
            style="height: 20px; width: 200px"
            v-model="formData.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item ref="upLoad" prop="logoUrl" label="品牌LOGO">
          <el-upload
            class="avatar-uploader"
            action="http://101.43.227.123:5555/app-prod/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <template #tip>
              <div>上传图片必须是jpg且不能大于2M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import trademarkApi from "@/api/mine/trademark";
import { Message } from "element-ui";
export default {
  name: "Trademark",
  data() {
    var validTrademarkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("名称不能为空"));
      }
      if (value.length < 5) {
        return callback(new Error("品牌需大于4个字"));
      }
      return callback();
    };
    var valiImageUrl = (rule, value, callback) => {
      if (!this.formData.logoUrl) {
        return callback(new Error("请上传文件"));
      }
      return callback();
    };
    return {
      trademarks: [], //品牌列表
      total: 0,
      current: 1,
      pageSize: 3,
      dialogVisible: false,
      formData: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [{ validator: validTrademarkName, trigger: "blur" }],
        logoUrl: [
          { required: true, validator: valiImageUrl, trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.limit = pageSize;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    // 获取列表信息
    async trademarkList() {
      try {
        let { data } = await trademarkApi.getList({
          current: this.current,
          pageSize: this.pageSize,
        });
        console.log(data);
        this.trademarks = data.records;
        this.current = data.current;
        this.pageSize = data.size;
        this.total = data.total;
      } catch (error) {
        console.log(error);
      }
    },
    // 删除品牌
    async deleteOne(item) {
      try {
        await this.$alert(`确定删除${item.tmName}`, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        });
        await trademarkApi.deleteOne(item.id);
        Message.success("删除成功");
        this.trademarkList();
      } catch (error) {
        if (error == "cancle") return;
        Message.error(error);
      }
    },
    // 修改当前页
    setCurrent(current) {
      console.log(1);
      this.current = current;
    },
    setSize(pageSize) {
      this.pageSize = pageSize;
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.formData.logoUrl = res.data;
      this.$refs.upLoad.clearValidate();
    },
    // 文件上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 保存添加的属性
    async saveAdd() {
      try {
        await trademarkApi.add(this.formData);
        Message.success("保存成功");
        this.trademarkList();
      } catch (error) {
        Message.error("保存失败");
      } finally {
        this.dialogVisible = false;
      }
    },
    // 修改属性
    async saveEdit() {
      try {
        await trademarkApi.update(this.formData);
        Message.success("保存成功");
        this.trademarkList();
      } catch (error) {
        Message.error("保存失败");
      } finally {
        this.dialogVisible = false;
      }
    },
    onSave() {
      if (this.formData.id) {
        this.saveEdit();
      } else {
        this.saveAdd();
      }
    },
    // 编辑按钮
    editTrademark(item) {
      console.log(item);
      this.dialogVisible = true;
      this.formData = { ...item };
    },
    closeBefore() {
      this.formData = {};
    },
  },
  mounted() {
    this.trademarkList();
  },
  computed: {
    cpChange() {
      let { current, pageSize } = this;
      return {
        current,
        pageSize,
      };
    },
  },
  watch: {
    cpChange() {
      console.log(11);
      this.trademarkList();
    },
  },
};
</script>

<style scoped>
.avatar-uploader >>> .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
